package com.alex;

import static com.anythink.core.api.ATInitMediation.getStringFromMap;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.anythink.banner.unitgroup.api.CustomBannerAdapter;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.List;
import java.util.Map;

public class AlexGromoreBannerAdapter extends CustomBannerAdapter {
    private final String TAG = getClass().getSimpleName();
    boolean isC2SBidding = false;
    String slotId;
    AlexGromoreConfig mATConfig;
    private Map<String, Object> mNetworkMap;

    private TTNativeExpressAd mBannerAd; // Banner广告对象
    private View mBannerView;

    @Override
    public View getBannerView() {
        return mBannerView;
    }

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra,
                                    Map<String, Object> localExtra) {
        if (!(context instanceof Activity)) {
            notifyATLoadFail("", "Gromore: context must be activity");
            return;
        }
        if (!initAndVerifyRequestParams(context, serverExtra, localExtra)) {
            notifyATLoadFail("", "app_id or slot_id is empty!");
            return;
        }

        AlexGromoreInitManager.getInstance()
                .initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        //todo check need to support native render banner
                        //MediationAdSlot.Builder mediationAdSoltBuilder = MobrainATInitManager.getInstance()
                        //        .getMediationAdSoltBuilder(slotId);
                        //
                        //if (mediationAdSoltBuilder == null) {
                        //    mediationAdSoltBuilder = new MediationAdSlot.Builder();
                        //}

                        //start load Banner
                        AdSlot.Builder adSlotBuilder = new AdSlot.Builder().setCodeId(slotId)
                                .setImageAcceptedSize(mATConfig.mWidth, mATConfig.mHeight); // 单位px
                                //.setMediationAdSlot(mediationAdSoltBuilder.build());

                        AdSlot adSlot = adSlotBuilder.build();
                        TTAdNative adNativeLoader = TTAdSdk.getAdManager()
                                .createAdNative((Activity) context);//必须传入Activity才会有加载回调

                        adNativeLoader.loadBannerExpressAd(adSlot,
                                new TTAdNative.NativeExpressAdListener() {
                                    @Override
                                    public void onError(int errCode, String errMsg) {
                                        notifyATLoadFail("" + errCode, errMsg);
                                    }

                                    @Override
                                    public void onNativeExpressAdLoad(
                                            List<TTNativeExpressAd> list) {
                                        if (list != null && list.size() > 0) {
                                            mBannerAd = list.get(0);
                                            mBannerAd.setExpressInteractionListener(
                                                    new TTNativeExpressAd.ExpressAdInteractionListener() {
                                                        @Override
                                                        public void onAdClicked(View view, int i) {
                                                            if (mImpressionEventListener != null) {
                                                                mImpressionEventListener.onBannerAdClicked();
                                                            }
                                                        }

                                                        @Override
                                                        public void onAdShow(View view, int i) {
                                                            mNetworkMap = AlexGromoreConst.getNetworkMap(
                                                                    mBannerAd);
                                                            bindDislikeCallbackListener(
                                                                    mBannerView);
                                                            if (mImpressionEventListener != null) {
                                                                mImpressionEventListener.onBannerAdShow();
                                                            }
                                                        }

                                                        @Override
                                                        public void onRenderFail(View view,
                                                                                 String s, int i) {

                                                        }

                                                        @Override
                                                        public void onRenderSuccess(View view,
                                                                                    float v,
                                                                                    float v1) {

                                                        }
                                                    });

                                            mBannerView = mBannerAd.getExpressAdView();

                                            if (isC2SBidding) {
                                                runOnNetworkRequestThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        double price = 0;
                                                        try {
                                                            price = Double.parseDouble(
                                                                    mBannerAd.getMediationManager()
                                                                            .getBestEcpm()
                                                                            .getEcpm());//return cent
                                                            price = price / 100;//cast to yuan
                                                        } catch (Throwable t) {

                                                        }
                                                        if (price <= 0) {
                                                            price = AlexGromoreUtil.getBestPriceInCacheNew(
                                                                    mBannerAd);
                                                        }

                                                        mBiddingListener.onC2SBiddingResultWithCache(
                                                                ATBiddingResult.success(price,
                                                                        System.currentTimeMillis() + "",
                                                                        null, mATConfig.mCurrency),
                                                                null);
                                                    }
                                                });
                                            } else {
                                                if (mLoadListener != null) {
                                                    mLoadListener.onAdCacheLoaded();
                                                }
                                            }
                                        } else {
                                            notifyATLoadFail("",
                                                    "Gromore banner load fail:banner load success, but list is null");
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        notifyATLoadFail("", errorMsg);
                    }
                });
    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra,
                                       Map<String, Object> localExtra,
                                       ATBiddingListener biddingListener) {
        isC2SBidding = true;
        loadCustomNetworkAd(context, serverExtra, localExtra);
        return true;
    }

    private boolean initAndVerifyRequestParams(Context context, Map<String, Object> serverExtra,
                                               Map<String, Object> localExtra) {
        String appId = getStringFromMap(serverExtra, "app_id");
        slotId = getStringFromMap(serverExtra, "slot_id");

        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(slotId)) {
            return false;
        }
        mATConfig = new AlexGromoreConfig(context, serverExtra);
        mATConfig.parseBannerLocalData(localExtra);
        return true;
    }

    private void bindDislikeCallbackListener(View view) {
        //bind dislike with current show activity
        try {
            ViewParent targetViewParent = view.getParent();
            while (!(targetViewParent instanceof ViewGroup) && targetViewParent != null) {
                targetViewParent = targetViewParent.getParent();
            }
            if (targetViewParent != null) {
                Context atBannerViewContext = ((ViewGroup) targetViewParent).getContext();
                if (atBannerViewContext instanceof Activity) {
                    bindDislikeCallbackListener((Activity) atBannerViewContext, mBannerAd);
                } else {
                    Log.d(TAG, "bindDislike fail:ATBannerView is not instanceof Activity");
                }
            } else {
                if (view != null && view.getContext() instanceof Activity) {
                    bindDislikeCallbackListener((Activity) view.getContext(), mBannerAd);
                } else {
                    Log.d(TAG, "bindDislike fail:mActivity is not instanceof Activity");
                }
            }
        } catch (Throwable t) {
            Log.e(TAG, "bindDislike fail:" + t.getMessage());
        }
    }

    private void bindDislikeCallbackListener(Activity context, TTNativeExpressAd bannerAd) {
        bannerAd.setDislikeCallback(context, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int i, String s, boolean b) {
                if (mImpressionEventListener != null) {
                    mImpressionEventListener.onBannerAdClose();
                }
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @Override
    public void destory() {
        if (mBannerAd != null) {
            mBannerAd.destroy();
        }
    }


    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AlexGromoreInitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return AlexGromoreInitManager.getInstance().getNetworkName();
    }

    @Override
    public Map<String, Object> getNetworkInfoMap() {
        return mNetworkMap;
    }
}
